//
//  HMTabBar.swift
//  MyWeibo
//
//  Created by apple on 16/4/16.
//  Copyright © 2016年 apple. All rights reserved.
//

import UIKit

class HMTabBar: UITabBar {

    //定义一个闭包
    var composeButtonClickClosure : (()->())?

    //重写init方法来加载frame
    override init(frame: CGRect) {
        
        super.init(frame: frame)
        
        addSubview(composeButton)
        composeButton.bringSubviewToFront(self)
        
            }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    override func layoutSubviews() {
        
        //首先调用父类
        super.layoutSubviews()
        
        composeButton.center = CGPoint(x:self.bounds.width * 0.5,y: self.bounds.height * 0.5)
        
        //设置每一个按钮的宽度
        let itemW = self.frame.width * 0.2
        
        
        var index = 0
        //遍历当前item
        for value in subviews{
            
            if value .isKindOfClass(NSClassFromString("UITabBarButton")!){
                
                //设置宽度
                value.frame.size.width = itemW
              //设置x的值
                value.frame.origin.x = CGFloat(index) * itemW
                
                index++
                if index == 2 {
                    index++
                }
            }
            
        }
    }
    

    //添加按钮点击方法
    func composeButtonClick(){
        
        //调用闭包
        composeButtonClickClosure!()
        
    }
    
    //懒加载加号按钮
    private lazy var composeButton : UIButton = {
        
        //定义一个button
       let button = UIButton()
        
        //添加点击方法
        button.addTarget(self, action: "composeButtonClick", forControlEvents: UIControlEvents.TouchUpInside)
        
        //设置button的图片
        button.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: UIControlState.Normal)
        button.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: UIControlState.Highlighted)
        
        //设置不同状态下button的背景图片
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: UIControlState.Normal)
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: UIControlState.Highlighted)
        
        //设置控件自适应大小
        button.sizeToFit()
        
//        self.addSubview(button)
//        
//        button.bringSubviewToFront(self)

        return button
    }()
    

}
